using System.Linq;
using NewApp.Backend.Api.Entity;
using NewApp.Backend.Api.Params;
using NewApp.Backend.Api.Repository;
using NewApp.Backend.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;


namespace NewApp.Backend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]

    //这里的控制器是 Articles
    public class ArticlesController : ControllerBase
    {

        private IConfiguration _configuration;

        private IRepository<Articles> _articleRepository;

        private IRepository<ArticleToptens> _articleToptensRepository;
        private IRepository<Users> _usersRepository;
        private IRepository<ArticleLikes> _articleLikesRepository;
        private IRepository<ArticleComments> _articleCommentsRepository;
        private IRepository<ArticleReader> _articleReaderRepository;

        private IRepository<Administrators> _administratorsRepository;

        private TokenParameter _tokenParameter;

        public ArticlesController(IConfiguration configuration
        , IRepository<Articles> articleRepository
        , IRepository<ArticleToptens> articleToptensRepository
        , IRepository<Users> usersRepository
        , IRepository<ArticleLikes> articleLikesRepository
        , IRepository<ArticleComments> articleCommentsRepository
        , IRepository<ArticleReader> articleReaderRepository
        , IRepository<Administrators> administratorsRepository)
        {
            _configuration = configuration;
            _articleRepository = articleRepository;
            _articleToptensRepository = articleToptensRepository;
            _usersRepository = usersRepository;
            _articleLikesRepository = articleLikesRepository;
            _articleCommentsRepository = articleCommentsRepository;
            _articleReaderRepository = articleReaderRepository;
            _administratorsRepository = administratorsRepository;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }

        //获取所有文章

        [HttpGet]
        public dynamic Get([FromQuery] QueryWithPager query)
        {
            // get请求默认从url中获取参数，如果需要使用实体接收参数，需要FromQuery特性
            // var pageIndex = query.Pager.PageIndex;
            // var pageSize = query.Pager.PageSize;

            var keyword = string.IsNullOrEmpty(query.Keyword) ? "" : query.Keyword.Trim();



            var articles = _articleRepository.Table.ToList();//所有文章
            var ArticleToptens = _articleToptensRepository.Table.ToList();//所有文章排行
            var users = _administratorsRepository.Table.ToList();//所有用户

            //以文章表为主表
            var newList = articles.Select(x =>
            {
                var _users = users.Where(t => t.Id == x.FromUsersId).FirstOrDefault();//匹配用户
                var _articleToptens = ArticleToptens.Where(k => k.FromArticlesId == x.Id).FirstOrDefault();
                return new
                {
                    Id = x.Id,//文章id
                    FromUsersName = _users.AdministratorsUsername,//创建人
                    ArticleTitle = x.ArticlesTitle,//文章标题
                    ArticleSynopsis = x.ArticleSynopsis,//文章简介
                    ArticlesContent = x.ArticlesContent,//文章内容
                    ArticlesClassify = x.ArticlesClassify, //文章分类
                    ReadSum = _articleToptens.ReadSum,//阅读数量
                    LikeSum = _articleToptens.LikeSum,//喜欢总数
                    CommentSum = _articleToptens.CommentSum,//喜欢总数
                    ArticleCovers = x.ArticleCovers,//文章封面图
                    CreatedTime = x.CreatedTime,
                    Order = x.DisplayOrder,

                };
            });

            // 如果keyword不为空，则再去查询文章
            if (!string.IsNullOrEmpty(keyword))
            {
                //以文章表为主表 搜索
                newList = articles.Where(x => x.Id.ToString() == keyword
                || x.ArticlesContent.Contains(keyword)
                || x.ArticleSynopsis.Contains(keyword)
                || x.ArticlesTitle.Contains(keyword)).Select(x =>
                    {
                        // var isusers = _administratorsRepository.Table.ToList()
                        // .Where(d => d.AdministratorsUsername.Contains(keyword)).FirstOrDefault(); ;
                        var _users = users.Where(t => t.Id == x.FromUsersId).FirstOrDefault();//匹配用户
                        var _articleToptens = ArticleToptens.Where(k => k.FromArticlesId == x.Id).FirstOrDefault();

                        return new
                        {
                            Id = x.Id,//文章id
                            FromUsersName = _users.AdministratorsUsername,//创建人
                            ArticleTitle = x.ArticlesTitle,//文章标题
                            ArticleSynopsis = x.ArticleSynopsis,//文章简介
                            ArticlesContent = x.ArticlesContent,//文章内容
                            ArticlesClassify = x.ArticlesClassify, //文章分类
                            ReadSum = _articleToptens.ReadSum,//阅读数量
                            LikeSum = _articleToptens.LikeSum,//喜欢总数
                            CommentSum = _articleToptens.CommentSum,//喜欢总数
                            ArticleCovers = x.ArticleCovers,//文章封面图
                            CreatedTime = x.CreatedTime,
                            Order = x.DisplayOrder,

                        };
                    });
            }
            var a = articles.Where(x => x.Id.ToString() == keyword
                 || x.ArticlesContent.Contains(keyword)
                 || x.ArticlesTitle.Contains(keyword));

            return JsonHelper.Serialize(new
            {
                Code = 1000,
                Data = new
                {
                    Data = newList,
                    Articles = a,
                    // Pager = new
                    // {
                    //     pageIndex,
                    //     pageSize,
                    //     rowsTotal = users.Count()
                    // }
                    // rowsTotal = newList.Count()
                },
                Msg = "获取文章列表成功^_^"
            });
        }
        //获取指定文章

        [HttpGet("{id}")]
        public dynamic Get(int id)//需要接收一个从前端传过来的用户id
        {
            var article = _articleRepository.GetById(id);

            //获取此文章的点赞总数
            var likeSum = _articleToptensRepository.Table.ToList().Where(x => x.FromArticlesId == id).FirstOrDefault().LikeSum;

            //当有获取一次篇时文章 视为浏览量+1
            var toptens = _articleToptensRepository.Table.ToList();
            var _readSum = toptens.Where(x => x.FromArticlesId == article.Id).FirstOrDefault();

            _readSum.ReadSum = _readSum.ReadSum + 1;

            _articleToptensRepository.Update(_readSum);

            //当用户浏览时触发 并且只添加一次
            var readTable = _articleReaderRepository.Table;
            var _isNull = readTable.Where(x => x.FromUsersId == 1 && x.FromArticlesId == article.Id).Count();

            if (_isNull < 1)//数据库中该用户对该文章浏览大于等于1 不计入其中
            {
                var read = new ArticleReader
                {
                    FromUsersId = 1,//修改成从前端传来的用户id
                    FromArticlesId = article.Id
                };

                _articleReaderRepository.Insert(read);

            }

            return new
            {
                Code = 1000,
                Data = article,
                // ReadSum=_readSum,
                LikeSum = likeSum,
                // Read=read,
                Msg = "获取指定文章成功^_^"
            };
        }
        //添加文章
        [HttpPost]

        public dynamic Post(CreateArticle newArticle)
        {
            var fromUserId = newArticle.FromUsersId;
            var articleTitle = newArticle.ArticlesTitle.Trim();
            var articleSynopsis = string.IsNullOrEmpty(newArticle.ArticleSynopsis.Trim()) ? "无" : newArticle.ArticleSynopsis;//简介
            var ArticlesContent = newArticle.ArticlesContent.Trim();
            var ArticlesClassify = newArticle.ArticlesClassify.Trim();//分类
            var avatar = newArticle.avatar;//图片路径
            // var Remark = string.IsNullOrEmpty(newArticle.Remarks.Trim()) ? "" : newArticle.Remarks;//分类


            // var articleCovers = _articleCoversReaderRepository.Table.ToList().LastOrDefault();

            if (string.IsNullOrEmpty(articleTitle) && string.IsNullOrEmpty(ArticlesContent))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "文章标题或内容不能为空"
                };
            }
            if (string.IsNullOrEmpty(ArticlesClassify))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "文章分类不能为空···"
                };
            }



            var articles = new Articles
            {
                FromUsersId = newArticle.FromUsersId,//创建人Id
                ArticlesTitle = newArticle.ArticlesTitle,
                ArticleSynopsis = newArticle.ArticleSynopsis,
                ArticlesContent = newArticle.ArticlesContent,
                ArticlesClassify = newArticle.ArticlesClassify,
                // ArticleCovers = articleCovers.PicturePath,
                ArticleCovers = newArticle.avatar


                // Remarks = Remark
            };
            _articleRepository.Insert(articles);

            //同时创建此文章相关的Topten  (初始化)
            var topten = new ArticleToptens
            {
                FromArticlesId = articles.Id,
                LikeSum = 0,
                ReadSum = 0,
                CommentSum = 0
            };

            _articleToptensRepository.Insert(topten);


            return new
            {
                Code = 1000,
                Data = articles,
                Msg = "创建文章成功^_^"
            };
        }
        //修改文章
        [HttpPut("{id}")]
        public dynamic Put(int id, CreateArticle updateArticle)
        {
            var articlesTitle = updateArticle.ArticlesTitle.Trim();
            var articleSynopsis = string.IsNullOrEmpty(updateArticle.ArticleSynopsis.Trim()) ? "无" : updateArticle.ArticleSynopsis;
            var ArticlesContent = updateArticle.ArticlesContent.Trim();
            // var ArticlesClassify = updateArticle.ArticlesClassify.Trim();
            var ArticlesOder = updateArticle.DisplayOrder;
            // var Remarks = string.IsNullOrEmpty(updateArticle.Remarks.Trim()) ? "无" : updateArticle.Remarks;

            if (string.IsNullOrEmpty(articlesTitle) && string.IsNullOrEmpty(ArticlesContent))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "文章标题或者文章内容不能为空=_="
                };

            }

            var article = _articleRepository.GetById(id);

            if (article == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "要更新的文章不存在，请确认后重试=_="
                };
            }

            article.ArticlesTitle = updateArticle.ArticlesTitle;
            article.ArticleSynopsis = updateArticle.ArticleSynopsis;
            article.ArticlesContent = updateArticle.ArticlesContent;
            // article.ArticlesClassify = updateArticle.ArticlesClassify;
            article.DisplayOrder = updateArticle.DisplayOrder;
            // article.Remarks = Remarks;

            _articleRepository.Update(article);

            return new
            {
                Code = 1000,
                Data = article,
                Msg = "更新成功"
            };
        }

        //删除文章
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var dTopten = _articleToptensRepository.Table.Where(x => x.FromArticlesId == id).ToList();
            //删除文章的同时删除点赞里的对该篇文章的记录
            var dArticleLike = _articleLikesRepository.Table.Where(x => x.FromArticlesId == id).ToList();
            for (var i = 0; i < dArticleLike.Count(); i++)
            {
                _articleLikesRepository.Delete(dArticleLike[i].Id);//删除文章同时删除所有点赞记录
            }
            //删除文章的同时删除评论里的对该篇文章的记录
            var dArticleComment = _articleCommentsRepository.Table.Where(x => x.FromArticlesId == id).ToList();
            for (var i = 0; i < dArticleLike.Count(); i++)
            {
                _articleCommentsRepository.Delete(dArticleLike[i].Id);//删除文章同时删除所有点赞记录
            }

            _articleRepository.Delete(id);
            _articleToptensRepository.Delete(dTopten[0].Id);//删除文章的同时删除此文章的Topten记录

            return new
            {
                Code = 1000,
                Data = "",
                Msg = "删除文章成功^_^"
            };
        }
        /*对文章进行的操作  点赞 评论 浏览*/

        //点赞
        [AllowAnonymous]
        [HttpPost, Route("Like")]
        public dynamic Post(CreateLike createLike)
        {
            var FromUsersId = createLike.FromUsersId;//当前用户
            var FromArticlesId = createLike.FromArticlesId;//当前点赞文章

            var like = new ArticleLikes
            {
                FromUsersId = createLike.FromUsersId,
                FromArticlesId = createLike.FromArticlesId
            };

            _articleLikesRepository.Insert(like);

            //点赞同时我向点赞总数+1
            var toptens = _articleToptensRepository.Table.ToList();//拿到列表
            var _likeSum = toptens.Where(x => x.FromArticlesId == (FromArticlesId)).FirstOrDefault();

            _likeSum.LikeSum = _likeSum.LikeSum + 1;

            _articleToptensRepository.Update(_likeSum);

            return new
            {
                Code = 1000,
                Data = like,
                // LikeSum=_likeSum,
                Msg = "点赞成功"
            };
        }
        //查询点赞
        [HttpGet, Route("getLike")]
        public dynamic GetLikeStatus(int userId, int articleId)
        {
            var like = _articleLikesRepository.Table.ToList().Where(x => x.FromUsersId == userId && x.FromArticlesId == articleId).Count();
            if (like < 1)
            {
                //返回没点赞
                return new
                {
                    Code = 104,
                };
            }
            else
            {
                //已点赞
                return new
                {
                    Code = 1000,
                };
            }
        }
        //评论
        [AllowAnonymous]
        [HttpPost, Route("comment")]
        public dynamic Post(CreateComment createComment)
        {
            var FromUsersId = createComment.FromUsersId;//当前用户
            var FromArticlesId = createComment.FromArticlesId;//当前评论文章
            var ArticleCommentsContent = createComment.ArticleCommentsContent.Trim();//

            if (string.IsNullOrEmpty(ArticleCommentsContent))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "sorry，评论内容不能为空"
                };
            }

            var comment = new ArticleComments
            {
                FromUsersId = createComment.FromUsersId,
                FromArticlesId = createComment.FromArticlesId,
                ArticleCommentsContent = createComment.ArticleCommentsContent
            };

            _articleCommentsRepository.Insert(comment);

            //同时将Topten 中的评论总数+1
            var toptens = _articleToptensRepository.Table.ToList();
            var _commentSum = toptens.Where(x => x.FromArticlesId == (FromArticlesId)).FirstOrDefault();

            _commentSum.CommentSum = _commentSum.CommentSum + 1;

            _articleToptensRepository.Update(_commentSum);

            return new
            {
                Code = 1000,
                Data = _commentSum,
                // CommentSum=commentSum,
                Msg = "评论成功"
            };
        }
        //获取48小时阅读总数返回给前端

        [HttpGet, Route("GetReadSum")]
        public dynamic GetReadSum()
        {
            var dt = DateTime.Now.AddHours(-48);
            var list = _articleToptensRepository.Table.ToList().Where(x => x.CreatedTime >= dt).OrderByDescending(s => s.ReadSum).Select(x =>
                  {
                      var article = _articleRepository.Table.ToList().Where(t => t.Id == x.FromArticlesId).FirstOrDefault();

                      return new
                      {
                          Id = article.Id,
                          Title = article.ArticlesTitle,
                          ReadSum = x.ReadSum,
                          CreatedTime = article.CreatedTime,
                      };
                  });

            return new
            {
                Code = 1000,
                Data = list,
                Msg = "获取48小时阅读排序成功"
            };
        }
        //获取评论总数返回给前端

        [HttpGet, Route("GetCommentSum")]
        public dynamic GetCommentSum()
        {
            var dt = DateTime.Now.AddHours(-240);
            var list = _articleToptensRepository.Table.ToList().Where(x => x.CreatedTime >= dt).OrderByDescending(s => s.CommentSum).Select(x =>
                  {
                      var article = _articleRepository.Table.ToList().Where(t => t.Id == x.FromArticlesId).FirstOrDefault();

                      return new
                      {
                          Id = article.Id,
                          Title = article.ArticlesTitle,
                          CommentSum = x.CommentSum,
                          CreatedTime = article.CreatedTime,
                      };
                  });

            return new
            {
                Code = 1000,
                Data = list,
                Msg = "获取十天评论排序成功"
            };
        }
        //获取单独文章的评论 返回给前端
        [HttpGet, Route("GetArticleComment")]
        public dynamic GetArticleComment(int articleId)
        {

            var comment = _articleCommentsRepository.Table.ToList()
            .Where(x => x.FromArticlesId == articleId)
            .OrderByDescending(s => s.Id)
            .Select(t =>
            {
                var username = _usersRepository.Table.Where(z => z.Id == t.FromUsersId).FirstOrDefault();

                return new
                {
                    Username = username.Username,
                    Comment = t.ArticleCommentsContent,
                    CreateTime = t.CreatedTime
                };
            });

            return JsonHelper.Serialize(new
            {
                Code = 1000,
                Data = comment,
                Msg = "获取评论成功"
            });

        }

    }

}
